package com.guochu.utils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * @Author: luc
 * @Date: 2019-10-9 11:36
 */
public class DesEncrypt {

    private DesEncrypt(){}

    /**
     * 加密数据
     * @param Text 需要加密的内容
     * @param sKey 秘钥
     * @return
     */
    public static String Encrypt(String Text, String sKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {

        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(sKey.getBytes());

        //创建一个密匙工厂，然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secureKey = keyFactory.generateSecret(desKey);

        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");

        //用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, random);

        //现在，获取数据并加密
        //正式执行加密操作，需要使用base64解决乱码
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(cipher.doFinal(Text.getBytes()));
    }

    /**
     * 解密数据
     * @param Text 需要解密的内容
     * @param sKey 秘钥
     * @return
     */
    public static String Decrypt(String Text, String sKey) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, IOException {

        //先使用base64解码
        Base64.Decoder decoder = Base64.getDecoder();

        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(sKey.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey secureKey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, secureKey, random);

        // 真正开始解密操作
        return new String(cipher.doFinal(decoder.decode(Text)));
    }
}
